package com.xdjk.networkdemo.net;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;
import com.xdjk.networkdemo.XApplication;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zhanghs on 2017/8/16.
 */

public class HttpManager {
    //定义基本地址
    public static final String BASE_URL = "http://www.weather.com.cn";
    public static final String BASE_URL2 = "http://mobile.weather.com.cn/";
    public static final String BASE_URL3 = "http://172.20.191.212:8081/";
    //设置连接超时的值
    private static final int TIMEOUT = 30;
    //声明HttpService对象
    protected HttpService httpService;
    //声明HttpManager对象
    private volatile static HttpManager httpManager;

    //Date对象传递
    public Gson mGson;

    /*创建缓存路径*/
    private File cacheFile = null;
    private Cache cache = null;

    //缓存对象
    public Retrofit mRetrofit;
    public OkHttpClient mOkHttpClient;

    private static final int CONNECTION_TIMEOUT = 10;
    private static final int READ_TIMEOUT = 40;
    private static final int WRITE_TIMEOUT = 20;

    protected HttpManager() {
        mGson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        //创建缓存路径
        cacheFile = new File(XApplication.getContext().getCacheDir(), "HttpCache");
        Logger.d("cacheFile=====" + cacheFile.getAbsolutePath());
        cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
    }

    private OkHttpClient getOkHttpClient() {
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                //设置okhttp拦截器，这样做的好处是可以为你的每一个
                .addInterceptor(NetInterceptorUtil.LogInterceptor())
                //retrofit2的网络请求都增加相同的head头信息，而不用每一个请求都写头信息
                .addNetworkInterceptor(NetInterceptorUtil.HeaderInterceptor())
                .cache(cache)
                .build();
        return mOkHttpClient;
    }

    public HttpManager builder() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                //增加返回值为String的支持
                .addConverterFactory(ScalarsConverterFactory.create())
                //增加返回值为Gson的支持(以实体类返回)
                .addConverterFactory(GsonConverterFactory.create(mGson))
                //增加返回值为Oservable<T>的支持
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(getOkHttpClient())
                .build();
        httpService = mRetrofit.create(HttpService.class);
        return this;
    }

    public HttpManager builder(String url) {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(url)
                //增加返回值为String的支持
                .addConverterFactory(ScalarsConverterFactory.create())
                //增加返回值为Gson的支持(以实体类返回)
                .addConverterFactory(GsonConverterFactory.create(mGson))
                //增加返回值为Oservable<T>的支持
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(getOkHttpClient())
                .build();
        httpService = mRetrofit.create(HttpService.class);
        return this;
    }

    public HttpService getHttpService() {
        return httpService;
    }

    //使用单例模式
    public static HttpManager getInstance() {
        if (httpManager == null) {
            synchronized (HttpManager.class) {
                if (httpManager == null) {
                    httpManager = new HttpManager();
                }
            }
        }
        return httpManager;
    }

    /**
     * 处理http请求——RX
     *
     * @param pObservable
     * @param pSubscriber
     */
    public void doHttpRequest(Observable pObservable, Subscriber pSubscriber) {
        Observable observable = pObservable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        observable.subscribe(pSubscriber);
    }

}
